package org.dakuai.graphqldemo.graphql;

import graphql.schema.DataFetcher;
import org.dakuai.graphqldemo.domain.Book;
import org.dakuai.graphqldemo.repository.AuthorRepository;
import org.dakuai.graphqldemo.repository.BookRepository;
import org.springframework.stereotype.Component;

import java.util.Map;

@Component
public class GraphQLDataFetchers {

    BookRepository bookRepository;
    AuthorRepository authorRepository;

    public GraphQLDataFetchers(BookRepository bookRepository, AuthorRepository authorRepository) {
        this.bookRepository = bookRepository;
        this.authorRepository = authorRepository;
    }

    public DataFetcher getBookByIdDataFetcher() {
        return dataFetchingEnvironment -> {
            String bookId = dataFetchingEnvironment.getArgument("id");

            return bookRepository.findById(bookId).orElse(null);
        };
    }

    public DataFetcher getAuthorDataFetcher() {
        return dataFetchingEnvironment -> {
            Book book = dataFetchingEnvironment.getSource();
            String authorId = book.getAuthorId();
            return authorRepository.findById(authorId).orElse(null);
        };
    }

//    public DataFetcher getAuthorByIdDataFetcher() {
//        return dataFetchingEnvironment -> {
//            String authorId =  dataFetchingEnvironment.getArgument("id");
//
//            return authorRepository.findById(authorId).orElse(null);
//        };
//    }
}
